package cosplay.Services;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class CommonServices {
	public static int getPageFromRequest(HttpServletRequest req)
	{
		int page=1;
		if (req.getParameterMap().containsKey("page"))
		{
			if (stringIntCheck(req.getParameter("page"))>0)
				page=stringIntCheck(req.getParameter("page"));
		}
		return page;
	}
	public static int getIDFromRequest(HttpServletRequest req,String idname)
	{
		int id=0;
		if (req.getParameterMap().containsKey(idname))
		{
			if (stringIntCheck(req.getParameter(idname))>0)
				id=stringIntCheck(req.getParameter(idname));
		}
		return id;
	}
	public static String getLoggedUsername(HttpServletRequest req)
	{
		return req.getRemoteUser();
//		if (req.getParameterMap().containsKey("SPRING_SECURITY_LAST_USERNAME"))
//			return req.getParameter("SPRING_SECURITY_LAST_USERNAME");
//		else
//			return null;
	}
	public static int stringIntCheck(String ask)
	{
		if ((ask==null)||(ask.equals("")))
			return -1;
		for (char c:ask.toCharArray())
		{
			if(((c^48)>9)||((c^48)<0))
				return 0;
			//			 if ("1234567890".indexOf(c)==-1)
			//				 return false;
		}
		return Integer.valueOf(ask).intValue();
	}
	public static int getPageFromCount(int count)
	{
		if (count<1)
			return 0;
		int page=((count/10)*10==count)?(count/10):((count/10)+1);
		return page;
	}
	public static String getMessageFromRequest(HttpServletRequest req)
	{
		if (req.getParameterMap().containsKey("message"))
			return req.getParameter("message");
		else
			return null;
	}
	public static Date getDateFromRequest(HttpServletRequest req, String name)
	{
		if (req.getParameterMap().containsKey(name))
		{
			try {
				return new Date(new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter(name)).getTime());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				return null;
			}
		}
		else
		{
			return null;
		}
	}
	public static Date getDateFromString(String in)
	{
		try {
			return new Date(new SimpleDateFormat("yyyy-MM-dd").parse(in).getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}
	@SuppressWarnings("null")
	public String ChangeIntListToString(List<Integer> ids)
	{
		String result=null;
		if (ids.size()>0)
		{
			for (Integer id :ids)
			{
				result+=String.valueOf(id)+",";
			}
			result=result.substring(0, result.length()-1);
		}
		return result;
	}
}
